package p.ithorns.tools.translator.apt.utils;

import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Options;

/**
 * MarkingScanner
 *
 * @author HtL
 * @date 2025/5/6 12:42
 * @since 1.0.0
 */
public class MarkingScanner extends TreeScanner {

    private final JCTree source;

    private final Context context;

    public MarkingScanner(Context context, JCTree.JCClassDecl source) {
        this.context = context;
        this.source = source;
    }

    @Override
    public void scan(JCTree tree) {
        if (tree == null) {
            return;
        }
        setGeneratedBy(tree, source);
        super.scan(tree);
    }

    private <T extends JCTree> void setGeneratedBy(T node, JCTree sourceNode) {
        boolean inNetbeansEditor = inNetbeansEditor(context);
        boolean isParameter = isParameter(node);
        if (!inNetbeansEditor || isParameter) {
            node.pos = sourceNode.pos;
        }
    }

    private boolean inNetbeansEditor(Context context) {
        Options options = Options.instance(context);
        return (options.keySet().contains("ide") && !options.keySet().contains("backgroundCompilation"));
    }

    private  boolean isParameter(JCTree node) {
        return node instanceof JCTree.JCVariableDecl
                && (((JCTree.JCVariableDecl) node).mods.flags & Flags.PARAMETER) != 0;
    }

}